//
//  EFAPjtAddVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/12.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAPjtAddVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFAPjtAddTCell.h"
#import "EFAModel.h"
#import "EFADeviceVC.h"
#import "EFAMsgVC.h"
#import "EFAPjtMapVC.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "EFAPjtPlaceSelVC.h"

@interface EFAPjtAddVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFAPjtAddTCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *saveBarBtnItem;
@property (nonatomic, assign)   EFAPjtAddVCType viewType;
@property (nonatomic, readonly) EFAProjectModel *projectModel;
@property (nonatomic, strong) NSArray<NSArray<NSString *> *> *titleArray;
@property (nonatomic, strong) NSArray<NSArray<EFAPjtAddViewCfg *> *> *dataArray;
@end

static NSString *const kReuseCellId = @"EFAPjtAddTCell";
//static NSInteger const kRequestUserSize = 20;

@implementation EFAPjtAddVC

#pragma mark - life cycle
- (instancetype)initWithViewType:(EFAPjtAddVCType)viewType {
    self = [super init];
    if (self) {
        _viewType = viewType;
        if (viewType == EFAPjtAddVCTypeAdd) {
            _pjtItem = [[EFAPjtListItem alloc] init];
        }
    }
    return self;
}

- (instancetype)init {
    NSAssert(NO, @"use initWithViewType");
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

//- (BOOL)hidesBottomBarWhenPushed {
//    return self.viewType == EFAPjtManagerVCTypeManager;
//}

- (void)initNavigationBar {
    self.navigationItem.title = (self.viewType == EFAPjtAddVCTypeAdd) ? @"新增项目" : @"编辑项目";
    self.navigationItem.rightBarButtonItem = self.saveBarBtnItem;
    [self.saveBarBtnItem setEnabled:NO];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.emptyDataSetDelegate = self;
//    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
//    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
//    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有项目" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return self.titleArray.count;
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    if (section < self.titleArray.count) {
//        return self.titleArray[section].count;
//    }
    if (section < self.dataArray.count) {
        return self.dataArray[section].count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFAPjtAddTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.section < self.dataArray.count) {
        if (indexPath.row < self.dataArray[indexPath.section].count) {
            [cell configViewWithViewCfg:self.dataArray[indexPath.section][indexPath.row]];
        }
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 14.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section < self.dataArray.count) {
        if (indexPath.row < self.dataArray[indexPath.section].count) {
            EFAPjtAddViewCfg *cfg = self.dataArray[indexPath.section][indexPath.row];
            if ([cfg.keyDes isEqualToString:@"项目地址"]) {
                [self jumpToSelectAddressWithCfg:cfg];
            }
        }
    }
}

#pragma mark - EFAPjtAddTCellDelegate
- (void)pjtAddTCell:(EFAPjtAddTCell *)cell editChanged:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.section < self.dataArray.count) {
        if (indexPath.row < self.dataArray[indexPath.section].count) {
            EFAPjtAddViewCfg *cfg = self.dataArray[indexPath.section][indexPath.row];
            cfg.value = textField.text;
//            if ([cfg.keyDes isEqualToString:@"项目名称"]) {
//                self.pjtItem.efairyproject_name = textField.text;
//            } else if ([cfg.keyDes isEqualToString:@"项目负责人姓名"]) {
//                self.pjtItem.efairyproject_user_name = textField.text;
//            } else if ([cfg.keyDes isEqualToString:@"项目负责人手机号"]) {
//                self.pjtItem.efairyproject_user_phonenumber = textField.text;
//            } else if ([cfg.keyDes isEqualToString:@"项目备注"]) {
//                self.pjtItem.efairyproject_description = textField.text;
//            }
        }
    }
    self.saveBarBtnItem.enabled = [self checkSaveBtnState];
}

#pragma mark - event response
- (void)addBarBtnTapped:(UIBarButtonItem *)item {
    if (![self checkUserInput]) {
        return;
    }
    
    //请求服务器
    if (self.viewType == EFAPjtAddVCTypeAdd) {
        [self requestAddProject];
    } else {
        [self requestEditProject];
    }
}
#pragma mark - private methods
- (void)jumpToSelectAddressWithCfg:(EFAPjtAddViewCfg *)cfg {
//    EFALocationPickerVC *vc = [[EFALocationPickerVC alloc] initWithDataSource:nil];
//    vc.pickerLocationBlock = ^(CLLocationCoordinate2D location, NSString *locationName) {
//        cfg.value = locationName;
//        self.pjtItem.efairyproject_location_lat = location.latitude;
//        self.pjtItem.efairyproject_location_lng = location.longitude;
//        [self refreshWholeView];
//    };
    
    EFAPjtPlaceSelVC *vc = [[EFAPjtPlaceSelVC alloc] init];
    vc.successHandle = ^(CLLocationCoordinate2D location, NSString *address) {
        cfg.value = address;
        self.pjtItem.efairyproject_address = address;
        self.pjtItem.efairyproject_location_lat = location.latitude;
        self.pjtItem.efairyproject_location_lng = location.longitude;
        [self refreshWholeView];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

- (BOOL)checkUserInput {
    for (NSArray *sArray in self.dataArray) {
        for (EFAPjtAddViewCfg *cfg in sArray) {
            if (cfg.value.length < cfg.valueMinLen || cfg.value.length > cfg.valueMaxLen) {
                [MBProgressHUD showPromptWithAutoHideInView:self.view message:cfg.prompt];
                return NO;
            }
        }
    }
    return YES;
}

- (BOOL)checkSaveBtnState {
//    for (NSArray *sArray in self.dataArray) {
//        for (EFAPjtAddViewCfg *cfg in sArray) {
//            if (cfg.value.length < cfg.valueMinLen || cfg.value.length > cfg.valueMaxLen) {
//                return NO;
//            }
//        }
//    }
    return YES;
}

- (NSMutableDictionary *)parametersDictionary {
    NSMutableDictionary *mDic = [[NSMutableDictionary alloc] init];
    for (NSArray *sArray in self.dataArray) {
        for (EFAPjtAddViewCfg *cfg in sArray) {
            NSString *value = cfg.value ? cfg.value : @"";
            [mDic setObject:value forKey:cfg.key];
            // Key-Value来更改原始值
            [self.pjtItem setValue:value forKey:cfg.key];
        }
    }
    // 没有的参数也加进来，比如坐标
    [mDic setObject:@(self.pjtItem.efairyproject_location_lat) forKey:@"efairyproject_location_lat"];
    [mDic setObject:@(self.pjtItem.efairyproject_location_lng) forKey:@"efairyproject_location_lng"];
    [mDic setObject:@(1) forKey:@"efairyproject_fee_type"];
    [mDic setObject:@(self.pjtItem.efairyproject_id) forKey:@"efairyproject_id"];
    return mDic;
}

- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.saveBarBtnItem.enabled = [self checkSaveBtnState];
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}
- (void)tableViewRefresh:(id)sender {
//    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
//    [self requestUserListWithHeader:isHeader];
}
- (void)backToParent {
    if (self.successHandle) {
        self.successHandle();
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - network request
- (void)requestAddProject {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [self parametersDictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    NSLog(@"添加项目的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiProject] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"添加项目返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"添加项目成功"];
        temp.completionBlock = ^{
            [self backToParent];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"添加项目失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}
- (void)requestEditProject {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [self parametersDictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    NSLog(@"编辑项目的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiProject] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"编辑项目返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"编辑项目成功"];
        temp.completionBlock = ^{
            [self backToParent];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"编辑项目失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)saveBarBtnItem {
    if (!_saveBarBtnItem) {
        _saveBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(addBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _saveBarBtnItem;
}
- (NSArray<NSArray<NSString *> *> *)titleArray {
    if (!_titleArray) {
        _titleArray = @[@[@"项目名称"],
                        @[@"项目负责人姓名", @"项目负责人手机号", @"项目地址", @"项目备注"]];
    }
    return _titleArray;
}

- (NSArray<NSArray<EFAPjtAddViewCfg *> *> *)dataArray {
    if (!_dataArray) {
        EFAPjtAddViewCfg *cfg1 = ({
            EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
            cfg.key = @"efairyproject_name";
            cfg.keyDes = @"项目名称";
            cfg.value = self.pjtItem.efairyproject_name;
            cfg.keyboardType = UIKeyboardTypeDefault;
            cfg.isInput = YES;
            cfg.isTextField = YES;
            cfg.valueMinLen = 1;
            cfg.valueMaxLen = 24;
            cfg.prompt = @"请输入项目名称";
            cfg.enabled = YES;
            cfg.scanEnabled = NO;
            cfg;
        });
        
        EFAPjtAddViewCfg *cfg2 = ({
            EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
            cfg.key = @"efairyproject_user_name";
            cfg.keyDes = @"项目负责人姓名";
            cfg.value = self.pjtItem.efairyproject_user_name;
            cfg.keyboardType = UIKeyboardTypeDefault;
            cfg.isInput = YES;
            cfg.isTextField = YES;
            cfg.valueMinLen = 1;
            cfg.valueMaxLen = 24;
            cfg.prompt = @"请输入项目负责人姓名";
            cfg.enabled = YES;
            cfg.scanEnabled = NO;
            cfg;
        });
        
        EFAPjtAddViewCfg *cfg3 = ({
            EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
            cfg.key = @"efairyproject_user_phonenumber";
            cfg.keyDes = @"项目负责人手机号";
            cfg.value = self.pjtItem.efairyproject_user_phonenumber;
            cfg.keyboardType = UIKeyboardTypeNumberPad;
            cfg.isInput = YES;
            cfg.isTextField = YES;
            cfg.valueMinLen = 11;
            cfg.valueMaxLen = 11;
            cfg.prompt = @"请输入11位手机号";
            cfg.enabled = YES;
            cfg.scanEnabled = NO;
            cfg;
        });

        EFAPjtAddViewCfg *cfg4 = ({
            EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
            cfg.key = @"efairyproject_address";
            cfg.keyDes = @"项目地址";
            cfg.value = self.pjtItem.efairyproject_address;
            cfg.keyboardType = UIKeyboardTypeDefault;
            cfg.isInput = NO;
            cfg.isTextField = YES;
            cfg.valueMinLen = 1;
            cfg.valueMaxLen = 64;
            cfg.prompt = @"请选择项目地址";
            cfg.enabled = YES;
            cfg.scanEnabled = NO;
            cfg;
        });
        
        EFAPjtAddViewCfg *cfg5 = ({
            EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
            cfg.key = @"efairyproject_description";
            cfg.keyDes = @"项目备注";
            cfg.value = self.pjtItem.efairyproject_description;
            cfg.keyboardType = UIKeyboardTypeDefault;
            cfg.isInput = YES;
            cfg.isTextField = YES;
            cfg.valueMinLen = 0;
            cfg.valueMaxLen = 24;
            cfg.prompt = @"请输入项目备注";
            cfg.enabled = YES;
            cfg.scanEnabled = NO;
            cfg;
        });
        
        _dataArray = @[@[cfg1], @[cfg2, cfg3, cfg4, cfg5]];
    }
    return _dataArray;
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (EFAProjectModel *)projectModel {
    return [EFAModel sharedInstance].projectModel;
}

@end
